let db = require("../../db/db")
let fs = require('fs')

let guid = function () {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}

let handle = async function (action, data, log_info, req, res) {
	switch (action) {
		case "upload": {
			//example:
			//fieldname: 'file',
			//originalname: '360MMAssisEx.dll',
			//encoding: '7bit',
			//mimetype: 'application/x-msdownload',
			//destination: '../upload/',
			//filename: '1629182162603-45832260025710854000.dll',
			//path: '../upload/1629182162603-45832260025710854000.dll',
			//size: 243624
			let file = data.file;
			console.log(file);
			let g = guid();
			let fileFormat = (file.originalname).split(".");
			let type = fileFormat[fileFormat.length - 1].toLowerCase();
			let params = {
				guid: g,
				filename: file.filename,
				original_filename: file.originalname,
				type: type,
				size: file.size,
				dir: "",
				create_user: log_info.user_id
			}
			await db.add("insert into sys_file set ?", [params]);
			return { value: "./file/download/" + g };
			break;
		}
		case "download": {
			let guid = data.guid;
			let result = await db.query("select * from sys_file where guid=?", [guid]);
			if(!result.rows || result.rows.length==0) reject(new Error("未查到此文件:"+guid));
			let row = result.rows[0];
			let file_path = "../upload/" + row.filename;
			let originalname = row.original_filename			
			//console.log(row);
			console.log('下载文件....' + guid + " " + file_path + " " + originalname);
			return new Promise(function (resolve, reject) {
				fs.readFile(file_path, (err, data) => {
					if (err) {
						reject(err);
						return;
					}
					res.writeHead(200, {
						'Content-Disposition': 'attachment; filename=' + originalname,
						'content-type': 'application/octet-stream',
						'Access-Control-Allow-Origin': '*',
						'Access-Control-Allow-Headers': 'X-Requested-With',
						'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
					});
					fs.createReadStream(file_path).pipe(res);
					resolve();
				});
			})
			break;
		}
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };